<script setup lang="ts">
import { ref, reactive, getCurrentInstance } from "vue";

import { PureTableBar } from "@/components/RePureTableBar";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import upload from "@iconify-icons/ep/upload";
import Refresh from "@iconify-icons/ep/refresh";
import { Plus } from "@element-plus/icons-vue";
import type { UploadInstance, UploadProps, UploadRawFile } from "element-plus";
import { genFileId } from "element-plus";
import AppUtil from "@/utils/AppUtil";

import { useRoute } from "vue-router";
import Edit from "@iconify-icons/ep/edit";
//import log from "./comp/log.vue";
import Form from "@/components/Form.vue";
import labelM from "./labelM.vue";
const route = useRoute();
defineOptions({
  name: "labels"
});
const config = reactive({
  listUrl: "/api/v1/labels",
  addUrl: "/api/v1/labels",
  editUrl: "/api/v1/labels",
  deleteUrl: "/api/v1/labels/delete",
  detailUrl: "",
  title: "标签分组",

  /**搜索条件 */
  searchForm: [],
  /**
   * 添加/编辑表单
   */
  editForm: [
    //名称     goodsName
    {
      label: "名称",
      prop: "groupName",
      type: "input",
      input: {
        type: "text"
      },

      rules: [{ required: true, message: "请输入名称", trigger: "blur" }]
    },

    //排序 sort
    {
      label: "排序",
      prop: "viewSort",
      type: "input",
      input: {
        type: "number"
      },
      value: 1
    },
    //status 状态
    {
      label: "状态",
      prop: "status",
      type: "select",
      value: 0,
      select: {
        options: [
          { id: 0, name: "启用" },
          { id: 1, name: "禁用" }
        ]
      }
    }
  ],
  rules: {},
  formData: {},
  defaultData: {},

  /**
   * 表格列
   */
  columns: [
    {
      label: "名称",
      prop: "groupName",
      align: "left"
    },
    //排序
    {
      label: "排序",
      prop: "viewSort",
      align: "left",
      cellRenderer: ({ row }) => row.viewSort
    },

    {
      label: "状态",
      prop: "status",
      align: "left",
      cellRenderer: ({ row }) => {
        return row.status == 0 ? "启用" : "禁用";
      }
    },

    {
      label: "操作",
      prop: "action",
      width: 200,
      slot: "operation"
    }
  ]
});

const pData = reactive({
  /**
   * 表格数据
   */
  dataArr: [],
  /**
   * 表格加载
   */
  loading: false,
  /**请求中 */
  reqing: false,
  /**
   * 表格分页
   */
  pagination: {
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  },

  imgArr: [],
  searchData: {},
  showEdit: false,

  showM: false,
  id: ""
});

const instance = getCurrentInstance();
function update_click(item) {
  console.log("update_click", item);
  config.formData = item;

  config.editForm.map(item1 => {
    //处理封面初始化imgArr

    if (item1.type == "uploadOne") {
      item1.upload.fileArr = [
        {
          url: AppUtil.getAliImgUrlByH(item[item1.prop]),
          response: { code: 200, data: item[item1.prop] }
        }
      ];
    }
  });
  // // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  console.log("update_click editForm", item);

  pData.showEdit = true;
}
function add_click() {
  if (config.formData.sid) {
    //移除选中的编辑数据，保留上次新增数据
    config.formData = JSON.parse(JSON.stringify(config.defaultData));
    config.editForm.map(item1 => {
      //处理封面初始化imgArr
      if (item1.type == "uploadOne") {
        item1.imgArr = [];
      }
    });
  }

  // config.editForm=JSON.parse(JSON.stringify(config.editForm));
  pData.showEdit = true;
}

function handleSizeChange(val: number) {
  console.log(`${val} items per page`);
  pData.pagination.pageSize = val;
  reset_list();
}

function handleCurrentChange(val: number) {
  console.log(`current page: ${val}`);
  pData.pagination.currentPage = val;
  onSearch();
}
//请求轮播图数据
async function onSearch() {
  pData.loading = true;

  AppUtil.request(
    {
      url: config.listUrl,
      method: "get",
      params: {
        ...pData.searchData,
        current: pData.pagination.currentPage,
        size: pData.pagination.pageSize
      }
    },
    res => {
      console.log("onSearch", res);

      // res.data.records.map(item => {
      //   let imgArr = [];
      //   let bigArr = [];
      //   item.pg_hb &&
      //     item.pg_hb.map(item1 => {
      //       imgArr.push(AppUtil.getAliImgUrlByW(item1, 200));
      //       bigArr.push(AppUtil.imgHost + item1);
      //     });
      //   item.imgArr = imgArr;
      //   item.bigArr = bigArr;
      // });
      pData.dataArr = res.data.records;
      pData.pagination.total = res.data.total * 1;
      pData.pagination.currentPage = res.data.current * 1;
    },
    b => (pData.loading = false)
  );
}
onSearch();

function handleDelete(item) {
  AppUtil.request(
    {
      url: config.deleteUrl,
      method: "PUT",
      data: {
        sidList: [item.sid]
      }
    },
    res => {
      onSearch();
    }
  );
}

function search_click() {
  reset_list();
}
/**搜索第一页的数据 */
function reset_list() {
  pData.pagination.currentPage = 1;
  onSearch();
}
function submitForm() {
  submit_form();
  // if (pData.imgArr.length < 1) {
  //   return instance.proxy.$alert("请选择图片");
  // }
  // let img = pData.imgArr[0];
  // //图片已经上传过
  // if (img.response && img.response.code == 200) {
  //   return submit_form();
  // }
  // //上传图片
  // upload1.value!.submit();
}
/**
 * 提交表单
 */
function submit_form() {
  instance.proxy.$refs["vForm"].validate(valid => {
    if (!valid) return;
    pData.reqing = true;

    // return console.log('formData',formData);
    //config.formData 移除sid
    let formData = JSON.parse(JSON.stringify(config.formData));
    delete formData.sid;

    AppUtil.request(
      {
        url: config.formData.sid
          ? config.editUrl + "/" + config.formData.sid
          : config.addUrl,
        method: config.formData.sid ? "put" : "post",
        data: formData
      },
      res => {
        // console.log("banner", res);
        instance.proxy.$message.success(
          config.formData.sid ? "修改成功" : "添加成功"
        );
        onSearch();
        pData.showEdit = false;
      },
      b => {
        pData.reqing = false;
      }
    );
  });
}
function showM_click(item) {
  pData.showM = true;
  pData.id = item.sid;
}
</script>

<template>
  <div class="main">
    <el-form
      v-if="config.searchForm && config.searchForm.length > 0"
      :model="pData.searchData"
      class="search-form bg-bg_color w-[99/100] pl-8 pt-[12px]"
      style="padding-bottom: 5px"
      :inline="true"
    >
      <el-form-item
        v-for="(item, i) in config.searchForm"
        :key="i"
        :label="item.label"
        :prop="item.prop"
      >
        <el-select
          v-if="item.type === 'select'"
          v-model="pData.searchData[item.prop]"
          style="width: 200px"
          placeholder="请选择"
        >
          <el-option
            v-for="(option, j) in item.options"
            :key="j"
            :label="option.label || option.name"
            :value="option.value || option.id"
          />
        </el-select>
        <el-input
          v-else-if="item.type === 'input'"
          v-model="pData.searchData[item.prop]"
          :placeholder="item.input.placeholder"
          clearable
        />
        <el-date-picker
          v-else-if="item.type === 'datetimerange'"
          v-model="pData.searchData[item.prop]"
          type="datetimerange"
          start-placeholder="开始日期"
          end-placeholder="结束时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          style="width: 360px"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          :icon="useRenderIcon('ri:search-line')"
          :loading="pData.loading"
          @click="search_click"
        >
          搜索
        </el-button>
      </el-form-item>
    </el-form>

    <PureTableBar
      :title="config.title + '管理'"
      :columns="config.columns"
      @refresh="onSearch"
    >
      <template #buttons>
        <el-button
          v-if="config.addUrl"
          type="primary"
          :icon="useRenderIcon(upload)"
          @click="add_click"
        >
          新增{{ config.title }}
        </el-button>
      </template>
      <template v-slot="{ size, dynamicColumns }">
        <pure-table
          :data="pData.dataArr"
          :columns="dynamicColumns"
          :loading="pData.loading"
          :size="size"
          :pagination="pData.pagination"
          :paginationSmall="size === 'small' ? true : false"
          @page-size-change="handleSizeChange"
          @page-current-change="handleCurrentChange"
        >
          <template #operation="{ row }">
            <!-- 成员管理 -->
            <el-button
              class="reset-margin"
              link
              type="success"
              :icon="useRenderIcon(Edit)"
              :size="size"
              @click="showM_click(row)"
            >
              成员管理
            </el-button>
            <el-button
              class="reset-margin"
              link
              type="primary"
              :size="size"
              @click="update_click(row)"
            >
              修改
            </el-button>

            <el-popconfirm
              :title="`是否确认删除这条数据`"
              @confirm="handleDelete(row)"
            >
              <template #reference>
                <el-button
                  class="reset-margin"
                  link
                  type="primary"
                  :size="size"
                >
                  删除
                </el-button>
              </template>
            </el-popconfirm>
          </template>
        </pure-table>
      </template>
    </PureTableBar>
    <el-dialog
      v-model="pData.showEdit"
      align-center
      :title="`${config.formData.sid ? '修改' : '新增'}${config.title}`"
      :width="700"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding-right: 1.5rem">
        <Form ref="vForm" v-model="config" />
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showEdit = false">取消</el-button>
          <el-button
            type="primary"
            :loading="pData.reqing"
            @click="submitForm()"
          >
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <el-dialog
      v-model="pData.showM"
      align-center
      title="成员管理"
      width="80vw"
      draggable
    >
      <div style="max-height: 82vh; overflow-y: auto; padding: 0 1rem">
        <labelM v-if="pData.showM" :id="pData.id" />
      </div>

      <template #footer>
        <div class="cls-center">
          <el-button @click="pData.showM = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped lang="scss"></style>
